package es.ats.codington.festival.daos;


import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Blob;



import javax.imageio.ImageIO;



import es.ats.codington.festival.domain.Image;
import es.ats.codington.festival.exceptions.DAOException;
import es.ats.codington.festival.interfaces.daos.IImageDAO;
import es.ats.codington.festival.utils.ImageDataConnection;

public class ImageDAO implements IImageDAO{
	


	public ImageDAO(){
			
	}
	
		
	public boolean guardarImagen(String ruta,String nombre, Connection conn){
		  
		  		//conn = ImageDataConnection.getConnection();
		        String insert = "INSERT INTO image values(null,?,?)";
		        FileInputStream fis = null;
		        PreparedStatement ps = null;
		        try {
		            
		        	conn.setAutoCommit(false);
		            File file = new File(ruta);
		            fis = new FileInputStream(file);
		            ps = (PreparedStatement) conn.prepareStatement(insert);
		            ps.setString(1, nombre);
		            ps.setBinaryStream(2,fis,(int)file.length());
		            //ps.setString(1, "park.jpg");
		            //ps.setBlob(2, is);
		            
		            ps.executeUpdate();
		            conn.commit();
		            
		            return true;
		        } catch (Exception ex) {
		        	//Logger.getLogger(BaseDatos.class.getName()).log(Level.SEVERE, null, ex);
		         
		        }finally{
		            try {
		                ps.close();
		                fis.close();
		                //conn.close();
		            } catch (Exception ex) {
		            
		            }
		        }        
		        return false;
		    }

	
	public List<Image> getImagenes(Connection conn) {
	     //conn = ImageDataConnection.getConnection();
	     PreparedStatement st = null;
	     ResultSet rs = null;
	     
	        List<Image> lista = new ArrayList<Image>();
	        try {
	        	//st = conn.prepareStatement("select * from image");
	        	st = conn.prepareStatement("select nameimage, image from image");
	            rs = st.executeQuery(); 
	            while (rs.next())
	            {
	                Image imagen=new Image();
	                Blob blob = rs.getBlob("image");
	                String name = rs.getObject("nameimage").toString();
	                byte[] data = blob.getBytes(2, (int)blob.length());
	                BufferedImage img = null;
	                try {
	                    img = ImageIO.read(new ByteArrayInputStream(data));
	                } catch (IOException ex) {
	                 
	                }
	                
	                imagen.setName(name);
	                imagen.setImage(img);
	                lista.add(imagen);
	            }
	            rs.close();
	            st.close();
	           // conn.close();
	        } catch (SQLException ex) {
	            
	        }
	        return lista;
	    }   
	
	
	public Image getImageById(int idImage, Connection conn) throws DAOException{
		try{
	    	PreparedStatement pStmt = conn.prepareStatement("select image from image where idimage=? ");
	    	pStmt.setInt(1,idImage);
	    	ResultSet rs = pStmt.executeQuery();
	    	Image i = new Image();
			if (rs.next()) {
				Blob b=rs.getBlob("photo");
				InputStream stream = b.getBinaryStream();
				BufferedImage img = ImageIO.read(stream);
				i.setImage(img);
				i.setIdImage(idImage);
				//String type = rs.getString("type");
				//i.setType(type);
				return i;
			}
			else{
				throw new DAOException("DB getImageById failure: empty resulset");
			}
		} catch (Exception ex) {
			throw new DAOException("DB getImageById failure:"+ex.getMessage(), ex);
		}
	}


	public static void main(String[] args){
		  Connection conn;
		  List<Image> images = new ArrayList<Image>();
		  conn = ImageDataConnection.getConnection();
		  ImageDAO imgDAO = new ImageDAO();
		  String ruta = "C:\\Users\\JAVA101_01\\Desktop\\zoo.jpg";
		  String nombre = "img_zoo";
		  imgDAO.guardarImagen(ruta, nombre, conn);
		  images = imgDAO.getImagenes(conn);
		  System.out.println();
		
	}
}
